import 'env-base.scss';
import { addStyles } from './_utils';

function pageLoaded() {
  window.$('body').addClass('init');
}

/*
  .@@. ----------------------- requirejs configuration ----------------------- */
+(function(){
  let paths = {
    // Can ONLY be used in fetching local server resources (CORS)
    text: "https://unpkg.com/requirejs-text@2.0.15/text", 
    // See https://cdnjs.com/libraries/requirejs-plugins
    json: "https://cdnjs.cloudflare.com/ajax/libs/requirejs-plugins/1.0.3/json.min",
    
    jquery: "lib/jquery-global",
    lodash: "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min",
    modernizr: "https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min",
    detectizr: "https://cdnjs.cloudflare.com/ajax/libs/detectizr/2.2.0/detectizr.min",
    
    'jquery-placeholder': 'https://cdnjs.cloudflare.com/ajax/libs/jquery-placeholder/2.3.1/jquery.placeholder.min',
  };
  
  const $ = window.jQuery;
  const requirejs = window.requirejs;
  
  requirejs.config({
    baseUrl: window._site.siteUrl + '/assets/',
    paths,
  });
  
  requirejs(['json!assets.json'], (assetsJson) => {
    Object.keys(assetsJson).forEach((assetName) => {
      Object.keys(assetsJson[assetName]).forEach((fileType) => {
        if (fileType === 'js') {
          paths[`${assetName}*${fileType}`] = `${fileType}/${assetsJson[assetName][fileType].replace(/\.js$/, '')}`;
        } else if (fileType === 'css') {
          paths[`${assetName}*${fileType}`] = `${fileType}/${assetsJson[assetName][fileType]}`;
        }
      })
    })
    
    requirejs.config({ paths });
    
    // console.log(paths)
    
    // Browser & Version
    +function(){
      let features = [];
      Object.keys($.browser).forEach((key) => {
        if (key === 'version') {
          if ($.browser.msie) {
            features.push(`msie${$.browser[key].split('.')[0]}`);
          }
        } else {
          if ($.browser[key]) {
            features.push(key);
          }
        }
      });
    
      $('body').addClass(features.join(' '));
    }();
    
    // Load page scripts
    if (window._site.scriptName) {
      let deps = [];
      if (`${window._site.scriptName}*js` in paths)
        deps.push(`${window._site.scriptName}*js`);
      if (`${window._site.scriptName}*css` in paths)
        deps.push(`text!${window._site.scriptName}*css`);
    
      requirejs(deps, (init, pageCSS) => {
        if (pageCSS) {
          addStyles('__page-styles', pageCSS);
        }
        
        pageLoaded();
      });
    } else {
      pageLoaded();
    }
    
    // common components for all the pages
    requirejs(['jquery-placeholder'], (_1) => {
      $('.input-placeholder').placeholder();
    })
  })
  
})();